-- MopUpM
-- Created by chengb Mar/5/2015
-- 地牢扫荡

module("MopUpM", package.seeall);

------------------------------
-- 获取今日剩余扫荡次数
function getRemainMopUpTimes(dungeonId)
    -- 最多可扫荡次数
    local maxTimes = getMaxMopUpTimes(dungeonId);

    -- 已扫荡次数
    local curTimes = getCurMopUpTimes(dungeonId);

    return math.max(maxTimes - curTimes, 0);
end

-------------------------------
-- 获取每天最多可扫荡的次数
function getMaxMopUpTimes(dungeonId)
    local maxTimes = FormulaM.invoke("CALC_DAILY_MOP_UP_TIMES", ME.user);

    -- 根据迷宫类型的额外扫荡次数
    local type = DungeonAreaM.query(dungeonId, "type");
    maxTimes = maxTimes + FormulaM.invoke("CALC_ACTIVITY_MOP_UP_TIMES", type);

    return maxTimes;
end

-------------------------------
-- 获取今日已扫荡次数
function getCurMopUpTimes(dungeonId)
    local mopUpInfos = ME.user.dbase:query("mop_up_info");
    if type(mopUpInfos) ~= 'table' then
        return 0;
    end

    local mopUpInfo = mopUpInfos[dungeonId];
    if type(mopUpInfo) ~= 'table' then
        return 0;
    end

    local serverTime = TimeM.getServerTime();
    if serverTime >= (mopUpInfo.reset_time or 0) then
        -- 已经超过了重置时间
        return 0;
    end

    return mopUpInfo["times"] or 0;
end

---------------------------------
-- 判断扫荡功能是否激活
function isMopUpActive()
    local times = FormulaM.invoke("CALC_DAILY_MOP_UP_TIMES", ME.user);
    return times > 0;
end

---------------------------------
-- 判断能否扫荡
-- @param dungeonId  地牢id
-- @return 如果验证通过，返回true，否则返回错误码
function canMopUp(dungeonId)
    local areaInfo = DungeonAreaM.query(dungeonId);
    if not areaInfo then
        -- 地牢不存在
        return false;
    end

    if not isMopUpActive() then
        -- 扫荡功能尚未激活
        return "mop_up_unactive";
    end

    if ActivityDungeonM.isActivityDungeon(dungeonId) then
        -- 活动副本
        local info = ActivityDungeonM.getActivityByDungeonId(dungeonId);
        if not ActivityDungeonM.isGradePassById(info.id, 3) then
            -- 困难难度未通关
            return "sub_area_not_pass";
        end
    else
        if not DungeonAreaM.isAllSubAreaPassed(ME.user, dungeonId) then
            -- 子区域未通关
            return "sub_area_not_pass";
        end
    end

    if getRemainMopUpTimes(dungeonId) <= 0 then
        -- 扫荡次数已用完
        return "no_times";
    end

    local requireLife = areaInfo["mop_up_life"];
    local curLife = ME.user.dbase:query("life");
    if curLife < requireLife then
        -- 体力不足
        return "life_lack";
    end

    if ActivityDungeonM.isActivityDungeon(dungeonId) then
        local info = ActivityDungeonM.getActivityByDungeonId(dungeonId);
        if info["id"] and not ActivityM.isDuringActivity(info["id"]) then
            -- 活动结束了
            return false;
        end
    end

    return true;
end



